package com.yuven.appframework.util

import android.os.CountDownTimer
import android.widget.TextView
import com.yuven.baselib.utils.Logger
import java.lang.ref.WeakReference


object CountDownTimerUtils {

    var mTotalTimeMills = 0L

    private  var onTickListener: ((Long) -> Unit)? = null
    private  var onFinishListener: (() -> Unit)? = null

    private val mCountDownTimer: CountDownTimer
        get() {
            return object : CountDownTimer(getCountTimeMills(),1000){
                override fun onTick(millisUntilFinished: Long) {
                    if (onTickListener != null){
                        onTickListener?.let { it(millisUntilFinished/1000) }
                    }
                }

                override fun onFinish() {
                    mTotalTimeMills = 0L
                    if (onFinishListener != null){
                        onFinishListener?.let { it() }
                    }
                }

            }
        }





    fun start(totalTimeMills: Long){
        mTotalTimeMills = totalTimeMills+System.currentTimeMillis()
        mCountDownTimer.start()
    }


    fun continueCount(){
        mCountDownTimer.start()
    }


    fun cancel(){
        mCountDownTimer.cancel()
        onTickListener = null
        onFinishListener = null

    }


    fun getCountTimeMills(): Long{
        return  mTotalTimeMills -System.currentTimeMillis()
    }


    fun isCounting(): Boolean{
        return System.currentTimeMillis() < mTotalTimeMills
    }

    fun reset(){
        mTotalTimeMills = 0L
        onTickListener = null
        onFinishListener = null
    }


    fun setOnCountDownListener(onTick:((Long) -> Unit)?,onFinish:(() -> Unit)?){
        onTickListener = onTick
        onFinishListener = onFinish
    }




}

